package cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.controller.admin.goods;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.controller.admin.goods.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.util.BarcodeGenerator;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.dal.dataobject.goods.GoodsDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.dal.mysql.goods.GoodsMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goods.service.goods.GoodsService;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.goodsType.GoodsTypeMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.supplier.dal.dataobject.supplier.SupplierDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.goodInfo.supplier.dal.mysql.supplier.SupplierMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.logisModul.dal.dataobject.logisticsmodul.LogisticsModulDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.logisModul.dal.mysql.logisticsmodul.LogisticsModulMapper;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserImportExcelVO;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.servlet.http.HttpServletResponse;
import javax.validation.*;
import java.io.IOException;
import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import org.springframework.web.multipart.MultipartFile;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 小程序-商品")
@RestController
@RequestMapping("/qd/goods")
@Validated
public class GoodsController {

    @Resource
    private GoodsService goodsService;
    @Resource
    GoodsMapper goodsMapper;
    @Resource
    SupplierMapper supplierMapper;
    @Resource
    LogisticsModulMapper logisticsModulMapper;

    @GetMapping("getBarCode")
    @Operation(summary = "获取条形码")
    public CommonResult getBarCode(Integer id){
        String result="";
        GoodsDO goodsDO = goodsMapper.selectById(id);
        if (goodsDO==null)
            throw new ServiceException(500,"暂无数据");
//        if (goodsDO.getBarCode()==null){
            result = BarcodeGenerator.getUrl(goodsDO.getCode());
            goodsDO.setBarCode(result);
            goodsMapper.updateById(goodsDO);
//        }else {
//            result=goodsDO.getBarCode();
//        }
        return success(result);
    }

    @PostMapping("/create")
    @Operation(summary = "创建小程序-商品")
    @PreAuthorize("@ss.hasPermission('qd:goods:create')")
    public CommonResult<Integer> createGoods(@Valid @RequestBody GoodsDO createReqVO) {
//        return success(1);
        return success(goodsService.createGoods(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新小程序-商品")
    @PreAuthorize("@ss.hasPermission('qd:goods:update')")
    public CommonResult<Boolean> updateGoods(@Valid @RequestBody GoodsDO updateReqVO) {
        goodsService.updateGoods(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除小程序-商品")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('qd:goods:delete')")
    public CommonResult<Boolean> deleteGoods(@RequestParam("id") Integer id) {
        goodsService.deleteGoods(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得小程序-商品")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('qd:goods:query')")
    public CommonResult<GoodsDO> getGoods(@RequestParam("id") Integer id) {
        return success(goodsService.getGoods(id));
    }

    @GetMapping("/list")
    @Operation(summary = "获得小程序-商品列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('qd:goods:query')")
    public CommonResult<List<GoodsDO>> getGoodsList(@RequestParam("ids") Collection<Integer> ids) {
        return success(goodsService.getGoodsList(ids));
    }

    @GetMapping("/page")
    @Operation(summary = "获得小程序-商品分页")
    @PreAuthorize("@ss.hasPermission('qd:goods:query')")
    public CommonResult<PageResult<GoodsDO>> getGoodsPage(@Valid GoodsPageReqVO pageVO) {
        PageResult<GoodsDO> goodsPage = goodsService.getGoodsPage(pageVO);
        List<GoodsDO> list = goodsPage.getList();
        for (GoodsDO vo : list) {
            List<GoodSpecif> specif = JSON.parseArray(vo.getSpecif().toString(),GoodSpecif.class);
            if (specif!=null&&specif.size()>0){
                List<GoodSpecifChild> child = specif.get(0).getChild();
                if (child!=null&&child.size()>0){
                    vo.setGoodsPrice(child.get(0).getPrice());
                    vo.setGoodsSize(child.get(0).getNum());
                }
            }
        }
        goodsPage.setList(list);
        return success(goodsPage);
    }

    @Resource
    GoodsTypeMapper goodsTypeMapper;

    @PostMapping("/importGoods")
    @Operation(summary = "导入商品")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult importGoods(@RequestParam("file") MultipartFile file) throws IOException {
        List<GooodImportExcelVO> list = ExcelUtils.read(file, GooodImportExcelVO.class);
        if (list.size()==0)
            throw new ServiceException(500,"请输入数据");



        int i=2;
        for (GooodImportExcelVO vo : list) {
            if (vo.getNum()==null)
                throw new ServiceException(500,"第"+i+"行，请输入库存");
            if (vo.getPrice()==null)
                throw new ServiceException(500,"第"+i+"行，请输入价格");

            goodsMapper.insert(new GoodsDO(vo));
        }

        return success("");
    }


//    @PostMapping("/importGoods")
//    @Operation(summary = "导入商品")
//    @Transactional(rollbackFor = Exception.class)
//    public CommonResult importGoods(@RequestParam("file") MultipartFile file) throws IOException {
//        List<GooodImportExcelVO> list = ExcelUtils.read(file, GooodImportExcelVO.class);
//        if (list.size()==0)
//            throw new ServiceException(500,"请输入数据");
//        //供应商名称 供应商id
//        Map<String,Integer> supMap=new HashMap<>();
//        for (SupplierDO vo : supplierMapper.selectList()) {
//            supMap.put(vo.getName(),vo.getId());
//        }
//        //模版名称 模版id
//        Map<String,Integer> modelMap=new HashMap<>();
//        for (LogisticsModulDO vo : logisticsModulMapper.selectList()) {
//            modelMap.put(vo.getName(),vo.getId());
//        }
//        for (GooodImportExcelVO vo : list) {
//            Integer supplierId=null;
//            String supplierName=null;
//            Integer postalId=null;
//            String postalName=null;
//            if (vo.getSupName()!=null){
//                Integer value = supMap.get(vo.getSupName());
//                if (value!=null){
//                    supplierId=value;
//                    supplierName=vo.getSupName();
//                }
//            }
//            if (vo.getPostalName()!=null){
//                Integer value = modelMap.get(vo.getPostalName());
//                if (value!=null){
//                    postalId=value;
//                    postalName=vo.getPostalName();
//                }
//            }
//            goodsMapper.insert(new GoodsDO(vo,supplierId,supplierName,postalId,postalName));
//        }
//
//        return success("");
//    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出小程序-商品 Excel")
    @PreAuthorize("@ss.hasPermission('qd:goods:export')")
    public void exportGoodsExcel(@Valid GoodsExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<GoodsExcelVO> list=new ArrayList<>();
        for (GoodsDO vo : goodsMapper.selectList(exportReqVO)) {
            List<GoodSpecif> specif = JSON.parseArray(vo.getSpecif().toString(),GoodSpecif.class);
            if (specif!=null&&specif.size()>0){
                List<GoodSpecifChild> child = specif.get(0).getChild();
                if (child!=null&&child.size()>0){
                    vo.setGoodsPrice(child.get(0).getPrice());
                    vo.setGoodsSize(child.get(0).getNum());
                }
            }
            list.add(new GoodsExcelVO(vo));
        }

        ExcelUtils.write(response, "商品表.xls", "数据", GoodsExcelVO.class, list);
    }

    @PostMapping("/addGoodsFile")
    @Operation(summary = "批量上传图片")
    public CommonResult addGoodsFile(@RequestBody GoodsFile vo) {
        for (GoodsDO dto : vo.getList()) {
            GoodsDO goodsDO = goodsMapper.selectById(dto.getId());
            goodsDO.setImg(dto.getImg());
            goodsMapper.updateById(goodsDO);
        }
        return success("");
    }

}
@Data
class GoodsFile{
    List<GoodsDO> list;
}